import Vue from 'vue'
import store from "@/store";
import VueRouter from 'vue-router'
import Login from '../views/Login.vue';


Vue.use(VueRouter)

const routes = [
    {
        path: '/' ,
        name: 'Login',
        component: Login
    },
    {
        path: '/404',
        name: '404',
        component: () => import('../views/404.vue')
    },
    {
        path: '/login',
        redirect:  '/'
    },

]

const router = new VueRouter({
    mode: 'history',
    base: process.env.BASE_URL,
    routes
})

// 重置路由
export const resetRouter = () => {
    router.matcher = new VueRouter({
        mode: 'history',
        base: process.env.BASE_URL,
        routes
    })
}



// 刷新页面会重置路由
export const setRoutes = () => {
    const storeMenus = localStorage.getItem('menus');
    if (storeMenus) {

        // 拼装动态路由
        const indexRoute = {
            path: '/index',
            name: 'index',
            component: () => import('../views/Index.vue'),
            redirect: '/home',
            children: []
        }
        const menus = JSON.parse(storeMenus)
        menus.forEach(menu => {
            if (menu.path) {
                let itemMenu = {
                    path: menu.path,
                    name: menu.mname,
                    component: () => import('../views/' + menu.pagePath + '.vue')
                }
                indexRoute.children.push(itemMenu)
            } else if (menu.children.length) {
                menu.children.forEach(child => {
                    if (child.path) {
                        let itemMenu = {
                            path: child.path,
                            name: child.mname,
                            component: () => import('../views/' + child.pagePath + '.vue')
                        }
                        indexRoute.children.push(itemMenu)
                    }
                })
            }
        })
        // 获取当前的路由对象名称数组
        const currentRoutes = router.getRoutes().map(v => v.name)
        if (!currentRoutes.includes('index')) {
            // 动态添加到路由对象
            router.addRoute(indexRoute)
        }
    }
}

// 重置就在setRoutes一次
setRoutes()


router.beforeEach((to, from, next) => {
    localStorage.setItem('currentPathName', to.name)    //设置当前的路由名称，为了在header中使用
    store.commit("setPath")   //触发store的数据更新


    // 未找到路由的情况
    if (!to.matched.length) {
        const storeMenus = localStorage.getItem("menus")
        if (storeMenus) {
            next("/404")  // 放行路由
        } else {
            next("/")
        }
    }
    next()


})

export default router
